<!-- 商品列表组件 <good-list :list="xx"></good-list> -->
<template>
    <view class="good-list" :style="{ top: stickyHeight + 'rpx' }">
      <!--产品详情弹窗-->
        <u-popup
            :safeAreaInsetBottom="true"
            :show="showGoodSelect"
            :round="40"
            mode="center"
            :closeable="true"
            @close="goodClose"
            :customStyle="currentGoodStyle"
            @touchmove.stop
        >
            <view class="current-good-box" v-if="currentGood != []">
                <view class="good-name">
                    <text>
                        {{ currentGood.goodName }}
                    </text>
                </view>
                <view class="good-img">
                    <image :src="currentGood.goodImg" mode="widthFix" />
                </view>
                <view class="good-desc"> 菜品介绍</view>
                <view class="good-bottom good-bottom-padding">
                    <view class="good-price" style="font-size: 34upx">
                        <view class="red">
                            ￥{{ currentGood.goodPrice }}
                            <view style="margin-left: 10rpx">
                                <u-tag
                                    text="会员价"
                                    type="warning"
                                    size="mini2"
                                    :plain="true"
                                    v-if="currentGood.goodType == 1"
                                ></u-tag>
                                <u-tag
                                    text="特价"
                                    type="error"
                                    size="mini2"
                                    v-if="currentGood.goodType == 2"
                                ></u-tag>
                            </view>
                        </view>
                        <view class="gray" v-if="currentGood.oldPrice > 0">
                            ￥{{ currentGood.oldPrice }}
                        </view>
                    </view>
                    <good-plus class="good-plus" :good="currentGood" :isCart="isCart"></good-plus>
                </view>
            </view>
        </u-popup>
      <!--产品规格弹窗-->
        <u-popup
            :safeAreaInsetBottom="true"
            :show="showGoodSpec"
            :round="40"
            mode="bottom"
            :closeable="true"
            @close="specClose"
            @touchmove.stop
        >
            <view class="current-good-spec-box" v-if="currentGood != []">
                <view class="title">
                    <view class="left">
                        <image :src="currentGood.goodImg" mode="widthFix" />
                    </view>
                    <view class="right">
                        <text>{{ currentGood.goodName }}</text>
                        <view class="btn" @click="resetSpec">
                            <u-button text="重选" plain size="small" type="primary"></u-button>
                        </view>
                    </view>
                </view>
                <view class="munber">
                    <view>数量</view>
                    <view>
                        <u-number-box
                            v-model:value="currentGood.currentGoodNumber"
                            step="1"
                            :min="1"
                        >
                            <view slot="minus" class="minus">
                                <u-icon name="minus" size="26rpx"></u-icon>
                            </view>
                            <text
                                slot="input"
                                class="input"
                                :style="{
                                    width: '60rpx',
                                    textAlign: 'center',
                                }"
                            >
                                {{ currentGood.currentGoodNumber }}
                            </text>
                            <view slot="plus" class="plus">
                                <u-icon name="plus" color="#FFFFFF" size="26rpx"></u-icon>
                            </view>
                        </u-number-box>
                    </view>
                </view>
                <scroll-view class="groups" :scroll-y="true">
                    <view class="group-box" v-for="(group, g) in currentGood.groups" :key="g">
                        <view class="group-title">
                            {{ group.title }}
                            <text class="sub">
                                {{
                                    group.sub_title != undefined
                                        ? "（" + group.sub_title + "）"
                                        : ""
                                }}
                            </text>
                        </view>
                        <view class="group-specs">
                            <view
                                :class="{
                                    spec: true,
                                    select: spec.select,
                                }"
                                v-for="(spec, s) in group.specs"
                                :key="s"
                            >
                                <text @click="selectSpec(g, s)">
                                    {{ spec.name }}
                                </text>
                                <text
                                    v-if="spec.price > 0"
                                    style="margin-left: 8rpx"
                                    @click="selectSpec(g, s)"
                                >
                                    {{ spec.price > 0 ? "￥" + spec.price : "" }}
                                </text>
                                <text
                                    v-if="spec.select_number > 1"
                                    style="margin-left: 8rpx"
                                    @click="selectSpec(g, s)"
                                >
                                    {{ spec.select_number > 1 ? "x" + spec.select_number : "" }}
                                </text>
                                <view
                                    style="margin-left: 20rpx; margin-right: -24rpx"
                                    v-if="spec.select_number == 1 && group.mustNumber == 0"
                                    @click="minusSpec(g, s)"
                                >
                                    <u-icon name="close-circle-fill" size="42"></u-icon>
                                </view>
                                <view
                                    style="margin-left: 20rpx; margin-right: -24rpx"
                                    v-if="spec.select_number > 1"
                                    @click="minusSpec(g, s)"
                                >
                                    <u-icon name="minus-circle-fill" size="42"></u-icon>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view style="height: 20rpx"> </view>
                </scroll-view>
                <view class="good-bottom good-bottom-padding">
                    <view class="good-price" style="font-size: 34upx">
                        <view class="red">
                            ￥{{ currentGood.currentGoodPrice
                            }}<text style="font-size: 28upx; color: #ccc">
                                {{
                                    currentGood.unit != ""
                                        ? "/" + currentGood.unit
                                        : currentGood.unit
                                }}
                            </text>
                            <text class="sub" style="font-size: 26upx">
                                {{
                                    currentGood.currentGoodPlusPrice > 0
                                        ? "（已加价￥" + currentGood.currentGoodPlusPrice + "）"
                                        : ""
                                }}
                            </text>
                        </view>
                    </view>
                    <view>
                        <u-button
                            text="加入购物车"
                            shape="circle"
                            color="#f9ae3d"
                            iconColor="#f9ae3d"
                            @click="addToCart"
                        ></u-button>
                    </view>
                </view>
            </view>
        </u-popup>
        <block v-for="(item, i) in listTemp" :key="i">
            <view class="g-list">
                <view class="good-cls" :style="{ top: stickyHeight + 'rpx' }" v-if="showCls">
                    分类测试：{{ i }}
                </view>
                <block v-for="good in item" :key="good.id">
                    <block v-if="isCart && (good.number == undefined || good.number == 0)"> </block>
                    <block v-else>
                        <block v-if="good.spceGoods != undefined">
                            <block v-for="(good, skey) in good.spceGoods" :key="good.id">
                                <block
                                    v-if="isCart && (good.number == undefined || good.number == 0)"
                                >
                                </block>
                                <view
                                    :id="'good' + good.id"
                                    :class="{
                                        'good-li': true,
                                        'is-c-out': good.is_c_out,
                                    }"
                                    v-else
                                >
                                    <image
                                        class="good-img"
                                        :src="good.goodImg"
                                        mode="widthFix"
                                        @click="goodSelect(good)"
                                    />
                                    <view class="flex-item">
                                        <view class="good-name" @click="goodSelect(good)">
                                            {{ good.goodName }}
                                        </view>
                                        <view class="good-bottom">
                                            <view class="good-price" @click="goodSelect(good)">
                                                <view class="red">
                                                    ￥{{ good.currentGoodPrice }}
                                                    <view style="margin-left: 10rpx">
                                                        <u-tag
                                                            text="会员价"
                                                            type="warning"
                                                            size="mini2"
                                                            :plain="true"
                                                            v-if="good.goodType == 1"
                                                        ></u-tag>
                                                        <u-tag
                                                            text="特价"
                                                            type="error"
                                                            size="mini2"
                                                            v-if="good.goodType == 2"
                                                        ></u-tag>
                                                    </view>
                                                </view>
                                                <view class="gray" v-if="good.oldPrice > 0">
                                                    ￥{{ good.oldPrice }}
                                                </view>
                                                <view class="spec-key">
                                                    {{ skey }}
                                                </view>
                                            </view>
                                            <good-plus :good="good" :isCart="isCart"></good-plus>
                                        </view>
                                    </view>
                                </view>
                            </block>
                        </block>
                        <block v-else>
                            <view
                                :id="'good' + good.id"
                                :class="{
                                    'good-li': true,
                                    'is-c-out': good.is_c_out,
                                }"
                            >
                                <image
                                    class="good-img"
                                    :src="good.goodImg"
                                    mode="widthFix"
                                    @click="goodSelect(good)"
                                />
                                <view class="flex-item">
                                    <view class="good-name" @click="goodSelect(good)">
                                        {{ good.goodName }}
                                    </view>
                                    <view class="good-bottom">
                                        <view class="good-price" @click="goodSelect(good)">
                                            <view class="red">
                                                ￥{{ good.goodPrice }}
                                                <view style="margin-left: 10rpx">
                                                    <u-tag
                                                        text="会员价"
                                                        type="warning"
                                                        size="mini2"
                                                        :plain="true"
                                                        v-if="good.goodType == 1"
                                                    ></u-tag>
                                                    <u-tag
                                                        text="特价"
                                                        type="error"
                                                        size="mini2"
                                                        v-if="good.goodType == 2"
                                                    ></u-tag>
                                                </view>
                                            </view>
                                            <view class="gray" v-if="good.oldPrice > 0">
                                                ￥{{ good.oldPrice }}
                                            </view>
                                        </view>
                                        <good-plus :good="good" :isCart="isCart"></good-plus>
                                    </view>
                                </view>
                            </view>
                        </block>
                    </block>
                </block>
            </view>
        </block>
        <view :style="{ height: cartHeight - noMoreHeight + 'rpx', width: '100%' }"> </view>
    </view>
</template>

<script>
import { mapState, mapGetters } from "vuex"; //引入mapState, mapGetters
export default {
    props: {
        list: {
            default() {
                return [];
            },
        },
        showCls: {
            type: Boolean,
            default() {
                return true;
            },
        },
        canSelect: {
            type: Boolean,
            default() {
                return true;
            },
        },
        isCart: {
            type: Boolean,
            default() {
                return false;
            },
        },
    },
    data() {
        return {
            currentGoodStyle: {
                width: "90%",
            },
            initGood: [],
        };
    },
    mounted() {
        uni.$on("specSelect", (good) => {
            let tmpGood = JSON.parse(JSON.stringify(good));

            // 初始化规格
            this.$set(tmpGood, "currentGoodPrice", tmpGood.goodPrice);
            this.$set(tmpGood, "currentGoodPlusPrice", 0);
            this.$set(tmpGood, "currentGoodNumber", 1);
            this.$set(tmpGood, "unit", "");
            for (var g = 0; g < tmpGood.groups.length; g++) {
                let group = tmpGood.groups[g];
                for (var s = 0; s < tmpGood.groups[g].specs.length; s++) {
                    let spec = tmpGood.groups[g].specs[s];
                    // 初始化规格的参数
                    this.$set(spec, "select_number", 0);
                    this.$set(spec, "select", false);
                    if (group.mustNumber > 0 && s == 0) {
                        spec.select = true;
                        this.goodPriceCalculation(spec.price, spec, tmpGood);
                    }

                    tmpGood.groups[g].specs[s] = spec;
                }
                tmpGood.groups[g] = group;
            }

            this.$store.commit("ordering/set", {
                showGoodSelect: false,
                showGoodSpec: true,
                currentGood: tmpGood,
            });

            // 拷贝商品
            let _tmp = JSON.stringify(tmpGood);
            this.initGood = JSON.parse(_tmp);
        });
    },
    computed: {
        ...mapState({
            cartHeight: (state) => state.cartHeight,
            noMoreHeight: (state) => state.noMoreHeight,
            cartGoods: (state) => state.ordering.cartGoods,
            showGoodSelect: (state) => state.ordering.showGoodSelect,
            showGoodSpec: (state) => state.ordering.showGoodSpec,
            currentGood: (state) => state.ordering.currentGood,
        }),
        ...mapGetters({
            navbarHeight: "getNavbarHeight",
            stickyHeight: "getStickyHeight",
        }),
        listTemp: function () {
            var list = this.list;
            if (typeof list == "object") {
                list = Object.values(list);
            }
            var arrTemp = [];
            var index = 0;
            var sectionCount = 2;
            for (var i = 0; i < list.length; i++) {
                index = parseInt(i / sectionCount);
                if (arrTemp.length <= index) {
                    arrTemp.push([]);
                }
                arrTemp[index].push(list[i]);
            }
            return arrTemp;
        },
    },
    methods: {
        addToCart() {
            let selectSpecs = [];
            let _tmp = JSON.stringify(this.currentGood);
            let currentGood = JSON.parse(_tmp);
            for (var g = 0; g < currentGood.groups.length; g++) {
                for (var s = 0; s < currentGood.groups[g].specs.length; s++) {
                    let spec = currentGood.groups[g].specs[s];
                    if (spec.select) {
                        let select_number = "";
                        if (spec.select_number > 1) {
                            select_number = select_number + "x" + spec.select_number;
                        }
                        selectSpecs.push(spec.name + select_number);
                    }
                }
            }
            const good_key = "_" + currentGood.id;
            const spec_key = selectSpecs.join("/");
            if (this.cartGoods[good_key] == undefined) {
                this.$set(this.cartGoods, good_key, { number: 0 });
                if (this.cartGoods[good_key].spceGoods == undefined) {
                    this.$set(this.cartGoods[good_key], "spceGoods", {});
                }
            }
            if (this.cartGoods[good_key].spceGoods[spec_key] == undefined) {
                this.$set(this.cartGoods[good_key].spceGoods, spec_key, currentGood);
                this.$set(this.cartGoods[good_key].spceGoods[spec_key], "number", 0);
                this.$set(this.cartGoods[good_key].spceGoods[spec_key], "spec_key", spec_key);
            }
            setTimeout(() => {
                this.cartGoods[good_key].number += currentGood.currentGoodNumber;
                this.cartGoods[good_key].spceGoods[spec_key].number +=
                    currentGood.currentGoodNumber;
                this.$store.commit("ordering/setCartStructure");
            }, 0);

            this.resetSpec();
            this.$store.commit("ordering/set", {
                showGoodSpec: false,
            });
        },
        resetSpec() {
            // 拷贝商品
            let _tmp = JSON.stringify(this.initGood);
            this.$store.commit("ordering/set", {
                currentGood: JSON.parse(_tmp),
            });
        },
        // 计算每一个分类的高度
        getRect(realBottom = 0) {
            return new Promise((resolve, reject) => {
                let hList = [];
                const query = uni.createSelectorQuery().in(this).selectAll(".g-list");
                let gPos = 0;
                query.boundingClientRect((data) => {
                      data.forEach((o, i) => {
                          if (i === 0) {
                              gPos = realBottom;
                          } else {
                              gPos += o.height;
                          }
                          hList.push(gPos);
                      });
                      resolve(hList);
                }).exec();
            });
        },
        goodSelect(good) {
            if (this.canSelect && !good.is_c_out) {
                this.$store.commit("ordering/set", {
                    showGoodSelect: true,
                    currentGood: good,
                });
            }
        },
        goodClose() {
            this.$store.commit("ordering/set", {
                showGoodSelect: false,
                currentGood: [],
            });
        },
        specClose() {
            this.$store.commit("ordering/set", {
                showGoodSpec: false,
                currentGood: [],
            });
        },
        // 选择规格
        selectSpec(g, s) {
            let group = this.currentGood.groups[g];
            let spec = group.specs[s];
            let price_process = 0;

            if (spec.calculation == "replace") {
                this.resetSpec();
            }

            // 单选
            if (!group.multiple) {
                for (var i = 0; i < group.specs.length; i++) {
                    group.specs[i].select_number = 0;
                    group.specs[i].select = false;
                }

                // 是否必须购买
                spec.select_number++;
                price_process += spec.price;
                spec.select = true;
            } else {
                // 可以购买多个
                if (spec.canPlus) {
                    spec.select_number++;
                    price_process += spec.price;
                    spec.select = true;
                } else {
                    if (spec.select) {
                        spec.select_number--;
                        price_process -= spec.price;
                        spec.select = false;
                    } else {
                        spec.select_number++;
                        price_process += spec.price;
                        spec.select = true;
                    }
                }
            }

            group.specs[s] = spec;
            this.currentGood.groups[g] = group;
            this.goodPriceCalculation(price_process, spec);
        },
        // 减少规格
        minusSpec(g, s) {
            let group = this.currentGood.groups[g];
            let spec = group.specs[s];

            spec.select_number--;
            if (spec.select_number == 0) {
                spec.select = false;
            }
            this.goodPriceCalculation(-spec.price, spec);

            group.specs[s] = spec;
            this.currentGood.groups[g] = group;
        },
        // 商品总价计算方式
        goodPriceCalculation(money, spec, good = undefined) {
            let currentGood = this.currentGood;
            if (good != undefined) {
                currentGood = good;
            }
            switch (spec.calculation) {
                case "plus":
                    currentGood.currentGoodPrice += money;
                    currentGood.currentGoodPlusPrice += money;
                    break;
                case "replace":
                    currentGood.currentGoodPrice = money;
                    currentGood.unit = spec.name;
                    break;
            }
        },
    },
};
</script>

<style lang="scss">
.current-good-spec-box {
    .title {
        height: 260rpx;
        border-bottom: 1rpx #ccc solid;
        .left {
            width: 30%;
            display: flex;
            justify-content: center;
            align-items: center;
            float: left;
            padding: 50rpx 0 30rpx 0;
            image {
                height: 180rpx !important;
                width: 180rpx !important;
            }
        }
        .right {
            display: flex;
            justify-content: space-between;
            flex-direction: column;
            padding: 50rpx 50rpx 30rpx 0;
            height: 180rpx;
            font-size: 30upx;
            .btn {
                width: 100%;
                button {
                    float: right;
                    width: 80rpx;
                    right: 30rpx;
                }
            }
        }
    }
    .munber {
        display: flex;
        justify-content: space-between;
        padding: 50rpx;
    }
    .groups {
        height: 600rpx;
        .group-title {
            padding: 20rpx 40rpx;
        }
        .group-specs {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 30rpx;
            .spec {
                font-size: 26upx;
                padding: 16rpx 30rpx;
                margin-left: 15rpx;
                margin-bottom: 15rpx;
                border-radius: 20rpx;
                border: 1rpx #c6c6c6 solid;
                background: rgba($color: #c6c6c6, $alpha: 0.2);
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .select {
                border: 1rpx #f9ae3d solid;
                background: rgba($color: #f9ae3d, $alpha: 0.2);
                color: #f9ae3d;
            }
        }
    }
}

.sub {
    font-size: 26upx;
    color: #666;
}

.current-good-box {
    .good-name {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 160rpx;
        border-bottom: 1rpx #ccc solid;
        text {
            width: 70%;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
        }
    }
    .good-img {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        image {
            margin: 50rpx;
            width: 400rpx !important;
            height: 400rpx !important;
        }
    }
    .good-desc {
        margin: 20rpx 20rpx 80rpx 20rpx;
        text-indent: 48rpx;
    }
}

.good-bottom {
    font-size: 30upx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .good-price {
        .red {
            color: red;
            display: flex;
            align-items: center;
            .u-tag {
                margin-left: 10rpx;
            }
        }
        .gray {
            color: #ccc;
            text-decoration: line-through;
            font-size: 26upx;
        }
        .spec-key {
            color: #999;
            font-size: 26upx;
        }
    }
}

.good-bottom-padding {
    padding: 30rpx;
    border-top: 1rpx #ccc solid;
}

.good-list {
    background-color: #fff;
    .good-cls {
        position: sticky;
        height: 90rpx;
        background-color: #fff;
        z-index: 2;
        font-size: 30upx;
        display: flex;
        align-items: center;
        padding-left: 20rpx;
    }
    .good-li {
        display: flex;
        align-items: center;
        padding: 20upx;
        border-top: 1rpx solid #eee;

        .good-img {
            width: 160upx;
            height: 160upx;
            margin-right: 20rpx;
        }

        .flex-item {
            flex: 1;
            height: 100%;
            .good-name {
                width: 100%;
                font-size: 26upx;
                line-height: 40upx;
                height: 80upx;
                margin-bottom: 20upx;
                overflow: hidden;
            }

            .good-info {
                .good-price {
                    float: left;
                    font-size: 26upx;
                    color: red;
                }
            }
        }
    }
}

.is-c-out {
    background-color: #fff;
    opacity: 0.3;
}

.minus {
    width: 40rpx;
    height: 40rpx;
    border-width: 1px;
    border-color: #e6e6e6;
    border-top-left-radius: 100rpx;
    border-top-right-radius: 100rpx;
    border-bottom-left-radius: 100rpx;
    border-bottom-right-radius: 100rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border: #ccc 1rpx solid;
}

.plus {
    width: 40rpx;
    height: 40rpx;
    background-color: #f9ae3d;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
